(function () {
	var ns = ij.pkg('core').namespaceString;
	ij.core.Scene = ij.core.Container.extend({
		init: function (config) {
			this._super(ij.apply({
				classname: ns+'.Scene',
				classes: ['ij-object', 'ij-container', 'ij-scene'],
				forces: []
			}, config));
			
			this.forces.push(new ij.core.GravityForce());
			this.forces.push(new ij.core.InertionForce());
			
			var _this = this;
			$(document).bind('keydown', function (event) {
				_this.controls.each(function(i, item) {
					item.startAction(event.keyCode);
				}, _this);
			}).bind('keyup', function (event) {
				_this.controls.each(function(i, item) {
					item.stopAction(event.keyCode);
				}, _this);
			});
			
			return this;
		},
		add: function (object) {
			if (object) {
				if (!(object instanceof ij.core.Layer)) {
					if (object instanceof ij.core.DisplayObject) {
						this._super(null);
						return this;
					}
					object = new ij.core.Layer(object);
				}
				this._super(object);
			}
			
			return this;
		},
		render: function () {
			this.intersectionHandler();
			
			this.objects.each(function (i, item) {
				if (item.applyForces) {
					item.applyForces(this.forces);
				}
				if (item.render) {
					item.render();
				}
			}, this);
			
			this.dispatchEvent('render');
		},
		intersectionHandler: function () {
			this.objects.each(function (index, layer) {
				for (var i = 0; i < layer.objects.length; i++) {
					for (var j = i+1; j < layer.objects.length; j++) {
						if (layer.objects[i] instanceof ij.core.GameObject &&
								layer.objects[j] instanceof ij.core.GameObject &&	
								(layer.objects[i].z == layer.objects[j].z || 
								!layer.objects[i].z || 
								!layer.objects[j].z)) {
							var res = layer.objects[i].intersects(layer.objects[j]);
							
							if (res.result) {
								console.log(res);
								if (res.top < 0 && res.bottom < 0) {
									if ((res.top - res.bottom) > 0) {
										layer.objects[i].y -= res.top/2;
										layer.objects[j].y += res.top/2;
										if (layer.objects[i].fY < 0) {
											layer.objects[i].fY = 0;
										}
									} else {
										layer.objects[i].y += res.bottom/2;
										layer.objects[j].y -= res.bottom/2;
										if (layer.objects[i].fY > 0) {
											layer.objects[i].fY = 0;
											layer.objects[i].state = 'stand';
										}
									}
								} else if (res.left < 0 && res.right < 0) {
									if ((res.left - res.right) > 0) {
										layer.objects[i].x -= res.left/2;
										layer.objects[j].x += res.left/2;
										if (layer.objects[i].fX < 0) {
											layer.objects[i].fX = 0;
										}
									} else {
										layer.objects[i].x += res.right/2;
										layer.objects[j].x -= res.right/2;
										if (layer.objects[i].fX > 0) {
											layer.objects[i].fX = 0;
										}
									}
								}
								
							}
						}
					}
				}
			}, this);
		}
	});
})();
